<template>
    <div class="container">
        <!-- 调整头部布局，添加搜索框 -->
        <div class="header">
            <div class="header-content">
                <div class="title-section">
                    <h1 class="page-title">项目信息列表</h1>
                    <div class="divider"></div>
                    <span class="subtitle">Total: {{ totalItems }}</span>
                </div>
                <div class="action-group">
                    <el-input
                        v-model="searchKeyword"
                        placeholder="输入项目名称/代码"
                        clearable
                        @input="handleSearch"
                        class="search-input"
                        size="large"
                    >
                        <template #prefix>
                            <el-icon class="search-icon"><Search /></el-icon>
                        </template>
                    </el-input>
                    <el-button type="primary" size="large" @click="handleCreate">新增项目</el-button>
                </div>
            </div>
        </div>
        <div class="table-container">
            <el-table
                :data="pageData"
                style="width: 100%"
                :height="tableHeight"
            >
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column label="父级分类">
                    <template #default="{ row }">
                        {{ getSupName(row.supFccId) }}
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="项目名称" />
                <el-table-column prop="code" label="项目代码" />
                <el-table-column prop="archive" label="归档状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.archive ? 'danger' : 'success'">
                            {{ row.archive ? '已归档' : '未归档' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" />
                <el-table-column prop="displayOrder" label="显示顺序" width="100" />
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button size="small" @click="editProject(row)">编辑</el-button>
                        <el-button
                            size="small"
                            type="danger"
                            @click="handleDeleteProject(row.id)"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination-container">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[20, 50, 100, 200]"
                :total="totalItems"
                layout="total, sizes, prev, pager, next, jumper"
                @current-change="handlePageChange"
                @size-change="handleSizeChange"
            />
        </div>
        <el-dialog v-model="dialogVisible" :title="formTitle" width="600px">
            <el-form :model="formData" label-width="100px">
                <el-form-item label="父级分类" required>
                    <el-select v-model="formData.supFccId" placeholder="请选择父级分类">
                        <el-option
                            v-for="type in projectTypes"
                            :key="type.id"
                            :label="type.name"
                            :value="type.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="项目名称" required>
                    <el-input v-model="formData.name" />
                </el-form-item>
                <el-form-item label="项目代码">
                    <el-input v-model="formData.code" />
                </el-form-item>
                <el-form-item label="归档状态">
                    <el-switch
                        v-model="formData.archive"
                        :active-value="1"
                        :inactive-value="0"
                    />
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="formData.description" type="textarea" />
                </el-form-item>
                <el-form-item label="显示顺序">
                    <el-input-number v-model="formData.displayOrder" :min="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import {
    getProjects,
    createProject,
    updateProject,
    deleteProject as deleteProjectApi
} from '@/api/projectApi'
import { getProjectTypes } from '@/api/projectTypeApi'

const currentPage = ref(1)
const pageSize = ref(20)
const totalItems = ref(0)
const pageData = ref([])
const allData = ref([]) // 存储所有数据
const projectTypes = ref([])
const searchKeyword = ref('') // 搜索关键词

const dialogVisible = ref(false)
const isEditMode = ref(false)
const formData = ref({
    supFccId: '',
    name: '',
    code: '',
    archive: 0,
    description: '',
    displayOrder: 0
})

const formTitle = computed(() => isEditMode.value ? '编辑项目' : '新增项目')

const tableHeight = computed(() => {
    return `calc(100vh - 400px)`
})

// 根据 ID 获取父级分类名称
const getSupName = (id) => {
    const type = projectTypes.value.find(type => type.id === id)
    return type? type.name : ''
}

// 初始化加载数据
const loadData = async () => {
    try {
        const [projectsRes, typesRes] = await Promise.all([
            getProjects({ page: currentPage.value, size: pageSize.value }),
            getProjectTypes({ size: 1000 })
        ])

        allData.value = projectsRes.data.content || []
        filterData()
        totalItems.value = projectsRes.data.total || 0
        projectTypes.value = typesRes.data.content || []
    } catch (error) {
        ElMessage.error('数据加载失败')
    }
}

// 过滤数据
const filterData = () => {
    let filtered = allData.value.filter(item => item.type === 1)
    if (searchKeyword.value!== '') {
        filtered = filtered.filter(item => {
            return item.name.includes(searchKeyword.value) || item.code.includes(searchKeyword.value)
        })
    }
    pageData.value = filtered
}

// 防抖搜索
let searchTimer = null
const handleSearch = () => {
    clearTimeout(searchTimer)
    searchTimer = setTimeout(() => {
        filterData()
    }, 300)
}

const handlePageChange = (newPage) => {
    currentPage.value = newPage
    loadData()
}

const handleSizeChange = (newSize) => {
    pageSize.value = newSize
    currentPage.value = 1
    loadData()
}

const handleCreate = () => {
    isEditMode.value = false
    formData.value = {
        supFccId: projectTypes.value[0]?.id || '',
        name: '',
        code: '',
        archive: 0,
        description: '',
        displayOrder: 0
    }
    dialogVisible.value = true
}

const editProject = (row) => {
    isEditMode.value = true
    formData.value = { ...row }
    dialogVisible.value = true
}

const submitForm = async () => {
    try {
        const api = isEditMode.value ? updateProject : createProject
        await api({
            ...formData.value,
            type: 1
        })
        dialogVisible.value = false
        await loadData()
        ElMessage.success('操作成功')
    } catch (error) {
        ElMessage.error('操作失败')
    }
}

const handleDeleteProject = async (id) => {
    try {
        await deleteProjectApi(id)
        await loadData()
        ElMessage.success('删除成功')
    } catch (error) {
        ElMessage.error('删除失败')
    }
}

onMounted(loadData)
</script>

<style scoped>
.container {
    padding: 20px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    padding: 10px 10px;
    border-bottom: 1px solid #e2e8f0;
    flex-shrink: 0;
}

.header-content {
    max-width: 1440px;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 5px 5px;
}

.title-section {
    display: flex;
    align-items: center;
    gap: 24px;
}

.page-title {
    font-size: 20px;
    font-weight: 600;
    color: #1e293b;
    margin: 0;
    letter-spacing: 0.5px;
}

.subtitle {
    color: #64748b;
    font-size: 14px;
}

.divider {
    width: 2px;
    height: 24px;
    background: #cbd5e1;
}

.action-group {
    display: flex;
    align-items: center;
    gap: 16px;
}

.search-input {
    width: 320px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.table-container {
    margin: 20px 0;
    box-sizing: border-box;
}

.pagination-container {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
}

:deep(.el-table) {
    --el-table-border-color: #e2e8f0;
    --el-table-header-bg-color: #f8fafc;
    --el-table-row-hover-bg-color: #f8fafc;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
}

:deep(.el-table th) {
    font-weight: 600;
    color: #475569;
}

:deep(.el-table td) {
    color: #475569;
}
</style>    